package handler

import (
	"CodeCover/internal/service"
	"CodeCover/internal/utils"
	"fmt"
	"net/http"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
)

type TaskRequest struct {
	Username  string `form:"username"`
	Page      int    `form:"page"`
	PageSize  int    `form:"pageSize"`
	StartDate string `form:"startDate"`
	EndDate   string `form:"endDate"`
}

type TaskHandler struct {
	taskService *service.TaskService
}

func NewTaskHandler(tSvc *service.TaskService) *TaskHandler {
	return &TaskHandler{taskService: tSvc}
}

func (h *TaskHandler) GetTasks(ctx *gin.Context) {

	var req TaskRequest
	// 绑定表单数据
	if err := ctx.ShouldBind(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	fmt.Printf("%#v\n", req)
	tasks, err := h.taskService.GetTasksByName(ctx.Request.Context(), req.Username, req.Page, req.PageSize, req.StartDate, req.EndDate)
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, tasks)
	// 返回

}

func (h *TaskHandler) GetOneTask(ctx *gin.Context) {
	// 1. 返回页面 tid内嵌
	fmt.Printf("get one task url %#v", ctx.Request.URL.Path)
	tid := ctx.Param("tid")
	fmt.Println("ONETID=", tid)
	ctx.HTML(http.StatusOK, "tree.html", gin.H{
		"tid": tid,
	})

}

func (h *TaskHandler) GetDirJson(ctx *gin.Context) {
	tid := ctx.Param("tid")
	fmt.Println("dirtid =", tid)
	task, err := h.taskService.GetTaskByTid(ctx, tid)

	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{
			"error": err.Error(),
		})
		return
	}
	fmt.Println(tid, task)
	moduleName, _ := h.taskService.GetModuleName(ctx.Request.Context(), tid)
	codeDir, _ := h.taskService.GetCodePath(ctx, tid)
	data, err := utils.Tree(filepath.Join(codeDir), moduleName)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}
	fmt.Println("data::", data)
	ctx.JSON(http.StatusOK, data)
}

func (h *TaskHandler) GetFile(ctx *gin.Context) {
	// "task/file?tid=xxx&path=xxx"

	tid := ctx.Query("tid")
	path := ctx.Query("path")
	parts := strings.Split(path, "/")
	path = strings.Join(parts[1:], "/")

	// path = ""
	task, err := h.taskService.GetTaskByTid(ctx.Request.Context(), tid)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err,
		})
		return
	}

	moduleName, err := h.taskService.GetModuleName(ctx, tid)
	if err != nil {
		fmt.Printf("%v", err)
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err,
		})
		return
	}
	fmt.Println(filepath.Join(task.AbsPath, "html", moduleName, path))

	ctx.File(filepath.Join(task.AbsPath, "html", moduleName, path))

}
